package com.mg.pluginwebservice.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLDecoder;

/**
 * Created by xiaolu on 2017/8/11.
 */
public class HttpRequestUtils {

    public final static String CONTENT_TYPE_JSON = "application/json";
    public final static String CONTENT_TYPE_X_FORM = "application/x-www-form-urlencoded";

    /**
     * post请求
     *
     * @param url       url地址
     * @param jsonParam 参数
     * @return getStatusCode
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam, String contentType) throws IOException {
        JSONObject jsonResult = null;
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        int statusCode = 404;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                StringEntity entity;
                if (contentType.equalsIgnoreCase(HttpRequestUtils.CONTENT_TYPE_X_FORM)) {
                    //解决中文乱码问题
                    entity = new StringEntity("param=" + jsonParam.getString("param"), "utf-8");
                } else {
                    //解决中文乱码问题
                    entity = new StringEntity(jsonParam.toString(), "utf-8");
                }

                entity.setContentEncoding("UTF-8");
                entity.setContentType(contentType);
                method.setEntity(entity);
            }
            HttpResponse httpResponse = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");

            //请求发送成功，并得到响应
            statusCode = httpResponse.getStatusLine().getStatusCode();

            /**请求发送成功，并得到响应**/
            if (statusCode == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(httpResponse.getEntity());
                /**把json字符串转换成json对象**/
                try {
                    jsonResult = JSONObject.parseObject(strResult);
                } catch (Exception e) {
                    JSONArray data = JSONArray.parseArray(strResult);
                    jsonResult = new JSONObject();
                    jsonResult.put("data", data);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }
}
